package com.example.myapplication.LoginRegister;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.example.myapplication.Data.UserData;
import com.example.myapplication.Tool.NetworkErrorTool;
import com.example.myapplication.R;
import com.example.myapplication.User.UserActivity;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private EditText name,pwd;
    private Button btnlogin;
    private TextView tvreg;

    private CheckBox cbRememberPwd;
    private Boolean bPwdSwitch = false;
//    private Mysql mysql;
//    private SQLiteDatabase db;
//    private SharedPreferences sp1,sp2;

    private final Gson gson = new Gson();
    //请求数据
    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据
    private Map entity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        name = findViewById(R.id.et_account);
        pwd = findViewById(R.id.et_pwd);
        btnlogin = findViewById(R.id.bt_login);
        tvreg = findViewById(R.id.tv_sign_up);
        cbRememberPwd = findViewById(R.id.cb_remember_pwd);
        final ImageView ivPwdSwitch = findViewById(R.id.iv_pwd_switch);

        //记住密码
        String spFileName = getResources()
                .getString(R.string.shared_preferences_file_name);
        String accountKey = getResources()
                .getString(R.string.login_account_name);
        String passwordKey =  getResources()
                .getString(R.string.login_password);
        String rememberPasswordKey = getResources()
                .getString(R.string.login_remember_password);

        SharedPreferences spFile = getSharedPreferences(
                spFileName,
                MODE_PRIVATE);
        String account = spFile.getString(accountKey, null);
        String password = spFile.getString(passwordKey, null);
        Boolean rememberPassword = spFile.getBoolean(
                rememberPasswordKey,
                false);
        if (account != null && !TextUtils.isEmpty(account)) {
            name.setText(account);
        }

        if (password != null && !TextUtils.isEmpty(password)) {
            pwd.setText(password);
        }
        cbRememberPwd.setChecked(rememberPassword);


        //密码可视性切换
        ivPwdSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bPwdSwitch = !bPwdSwitch;
                if (bPwdSwitch) {
                    ivPwdSwitch.setImageResource(
                            R.drawable.baseline_visibility_24);
                    pwd.setInputType(
                            InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    ivPwdSwitch.setImageResource(
                            R.drawable.baseline_visibility_off_24);
                    pwd.setInputType(
                            InputType.TYPE_TEXT_VARIATION_PASSWORD |
                                    InputType.TYPE_CLASS_TEXT);
                    pwd.setTypeface(Typeface.DEFAULT);
                }
            }
        });
        //转注册界面事件
        tvreg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                Toast.makeText(LoginActivity.this,"跳转到注册界面",Toast.LENGTH_SHORT).show();
            }
        });
        //登录事件
        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //记住密码
                String spFileName = getResources()
                        .getString(R.string.shared_preferences_file_name);
                String accountKey = getResources()
                        .getString(R.string.login_account_name);
                String passwordKey =  getResources()
                        .getString(R.string.login_password);
                String rememberPasswordKey = getResources()
                        .getString(R.string.login_remember_password);
                SharedPreferences spFile = getSharedPreferences(
                        spFileName,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = spFile.edit();

                if (cbRememberPwd.isChecked()) {
                    String password = pwd.getText().toString();
                    String account = name.getText().toString();

                    editor.putString(accountKey, account);
                    editor.putString(passwordKey, password);
                    editor.putBoolean(rememberPasswordKey, true);
                    editor.apply();
                } else {
                    editor.remove(accountKey);
                    editor.remove(passwordKey);
                    editor.remove(rememberPasswordKey);
                    editor.apply();
                }

                //post请求
                post();
            }
        });
    }
    private void post(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/user/login"
                    + "?password="+pwd.getText().toString()
                    + "&username="+name.getText().toString();

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, ""))
                    .build();
            Log.d("chenpengyu1111111111", String.valueOf(request));
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /*** 回调*/
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            NetworkErrorTool networkErrorTool = new NetworkErrorTool(LoginActivity.this);
            // 请求失败处理
            e.printStackTrace();
            networkErrorTool.showTimeoutDialog(); // 显示超时提示对话框
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("chenpengyu1111111111", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("chenpengyu1111111111", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse(); // 处理响应结果
                }
            });
        }
    };
    //登录
    private void handleResponse() {
        if (code == 200) {
            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();

            //将获取的数据存入UserData工具类。
            JsonObject jsonObject = gson.toJsonTree(data).getAsJsonObject();
            UserData userData = gson.fromJson(jsonObject, UserData.class);

            Intent intent = new Intent();
            intent.setClass(LoginActivity.this, UserActivity.class);

            // 将userData对象传递给UserActivity
            intent.putExtra("userData", userData);

            startActivity(intent);
        } else {
            if(msg != null) {
                Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        }
    }
}